$(document).ready(function() {
    $('input[id=downloader-plain]').hide();
    // Cria novos campos
    var ol;
    $('ol').on('click', '.buttonAdd', function() {
        ol = $(this).parents('ol');
        var li = ol.find('.clone').clone();

        li.removeClass('clone')
                .find('input.buttonAdd')
                .removeClass('buttonAdd')
                .addClass('buttonDelete').end()
                .find('input').val('').end();

        $(ol).append(li);
    });

    $('ol').on('click', '.buttonDelete', function() {
        var button = $(this).attr('id');
        if (button === "create-query") {
            $(this).closest('li').prev().remove();
            $(this).closest('li').remove();
        } else {
            $(this).closest('li').remove();
        }
    });

    // Pega os valores clicados na ontologia
    var newValue,
            valuesClicked;
    $(".conteudoMenu a").click(function(evt) {
        var key = $(this).parent(".conteudoMenu").parent("li").find(".itemMenu").attr("id");
        var value = $(this).attr("id");
        var select = "";
        newValue = key + "_" + value;
        valuesClicked = generatingArray(newValue);

        for (var i = 0; i < valuesClicked.length; i++) {
            if (i < valuesClicked.length - 1) {
                select += valuesClicked[i] + ", ";
            } else {
                select += valuesClicked[i];
            }
        }

        $('.varselect').html(select);
        evt.preventDefault();
    });

    // Adiciona os dados ao Array() no qual serão utilizados para construir o select query.
    var mapValuesQuery = new Array();
    function generatingArray(value) {
        if ($.inArray(value, mapValuesQuery) === -1) {
            mapValuesQuery.push(value);
        }
        return mapValuesQuery;
    }

    // Verifica se o array contém um determinado valor antes de adiciona-lo
    function checkArray(ArrayList, value) {
        if ($.inArray(value, ArrayList) === -1) {
            return true;
        }
        return false;
    }

    // Constrói o parameterListCondition
    var listCondition = new Array();
    function parameterListCondition() {
        $('ol[id=operator-attribute] li').each(function() {
            var value = $(this).find('input.operator').val() + " ?:" + $(this).find('input.attribute').val();
            if (checkArray(listCondition, value)) {
                listCondition.push(value);
            }
        });
        return listCondition;
    }

    var listParameter = new Array();
    function destinationParameter() {
        $('ol[id=parameters] li').each(function() {
            var value = $(this).find('input.parameters').val();
            if (checkArray(listParameter, value)) {
                listParameter.push(value);
            }
        });
        return listParameter;
    }

    var listQuery = new Array();
    function queryVCD() {
        var id = 1;
        $('ol[id=create-query] li').each(function() {
            var value = id + " ?:" + $(this).find('input.endpoint').val() + " ?:" + $(this).find('textarea.query').val();
            if (checkArray(listQuery, value)) {
                listQuery.push(value);
                id++;
            }
        });
        return listQuery;
    }

    $('input[name=create-plain]').click(function() {
        $.ajax({
            url: "../createplain",
            type: "Get",
            data: {
                name: $('input[id=name]').val(),
                type: $('input[id=type]:checked').val(),
                select: $('textarea[id=select]').val(),
                "parameterListCondition[]": parameterListCondition(),
                limit: $('input[id=limit]').val(),
                nameDestination: $('input[id=destination]').val(),
                "destinationParameter[]": destinationParameter(),
                "query[]": queryVCD()
            },
            error: function(responseXML) {
                console.log("ERROR: " + responseXML);
            },
            success: function(responseXML) {
                var blob = new Blob([responseXML], {type: 'application/xml;charset=utf-8'});

                $('input[id=downloader-plain]').show();
                $('input[id=downloader-plain]').on('click', function(e) {
                    e.preventDefault();
                    saveAs(blob, $('input[id=name]').val() + '.xml');
                });
            }
        });
    });
});